package com.czp.infosharingplatformapp.service.impl;

import com.czp.infosharingplatformapp.model.Comment;
import com.czp.infosharingplatformapp.model.Post;
import com.czp.infosharingplatformapp.model.User;
import com.czp.infosharingplatformapp.repository.CommentRepository;
import com.czp.infosharingplatformapp.repository.PostRepository;
import com.czp.infosharingplatformapp.repository.UserRepository;
import com.czp.infosharingplatformapp.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Comment createComment(Long postId, String content, Long userId, Long parentId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new RuntimeException("帖子不存在"));

        Comment parent = null;
        if (parentId != null) {
            parent = commentRepository.findById(parentId)
                    .orElseThrow(() -> new RuntimeException("父评论不存在"));
        }

        Comment comment = new Comment();
        comment.setContent(content);
        comment.setUser(user);
        comment.setPost(post);
        comment.setParent(parent);

        return commentRepository.save(comment);
    }

    @Override
    public List<Comment> getCommentsByPostId(Long postId) {
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new RuntimeException("帖子不存在"));
        return commentRepository.findByPost(post);
    }

    @Override
    public void deleteComment(Long commentId) {
        if (!commentRepository.existsById(commentId)) {
            throw new RuntimeException("评论不存在");
        }
        commentRepository.deleteById(commentId); // 删除评论
    }
}